var Tiny = require('tiny');

var Article = {
    id: String,
    title: String,
    content: String,
    publish: Date,
    images: String,
    link: String,
};

var dbName = 'data/dbArticles.tiny';

Tiny(dbName, function(err, db) {
    // 使用数据库实例db来操作数据。
});

var ArticleDAO = function() {};
module.exports = new ArticleDAO();

ArticleDAO.prototype.save = function(article, callback) {
    Tiny(dbName, function(err, db) {
        db.set(article.id, {
            title: article.title,
            content: article.content,
            publish: article.publish,
            images: article.images,
            link: article.link,
        }, function(err) {
            if (err) {
                err = 'Save tinydb err, id is ' + article.id + err
            };
            callback(err);
        });
    });
}

ArticleDAO.prototype.getById = function(articleId, callback) {
    Tiny(dbName, function(err, db) {
        db.get(articleId, function(err, result) {
            callback(err, result);
        });
    })
}

ArticleDAO.prototype.fetch = function(countNum, callback) {
    Tiny(dbName, function(err, db) {
        db.fetch({
            desc: 'publish',
            limit: countNum,
        }, function(doc, key) {
            //console.log('Found:', key);
            return true;
        }, function(err, results) {
            //console.log('Results:', results);
            if (err) {
                err = 'Fetch tinydb err, limitNum is ' + countNum + ' ' + err
            }
            callback(results, err);
        })
    })
}

ArticleDAO.prototype.removeOld = function(publish, callback) {
    Tiny(dbName, function(err, db) {
        db.find({
            $and: [{
                timestamp: {
                    $lte: publish
                }
            }, ]
        }, (function(err, results) {
            console.log('Results:', results);
            for (article in results) {
                db.remove(article.id, function(err) {
                    console.log('deleted');
                    callback(err);
                });
            };
            callback(err);
        }));
        db.compact(function(err) {
            console.log('done');
            callback(err);
        });
    })
}

ArticleDAO.prototype.compact = function(callback) {
    Tiny(dbName, function(err, db) {
        db.compact(function(err) {
            callback(err);
        });
    });
}

ArticleDAO.prototype.closeFile = function(callback) {
    Tiny(dbName, function(err, db) {
        db.close(function(err) {
            if (err) {
                err = 'Close tinydb err,   ' + err
            }
            callback(err);
        });
    });
}